//
//  AddBankCardViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/12/2.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "AddBankCardViewController.h"
#import "UIColor+Hex.h"
#import "AFHTTPRequestOperationManager.h"
#import "MBProgressHUD+MJ.h"
#import "HttpReauestParam.h"
#import "UserDefaultUtil.h"

#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度，兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度，兼容性测试
@interface AddBankCardViewController ()

@property NSArray *dataArray;
@property NSDictionary *chooseBank;


@end

@implementation AddBankCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    _dataArray = [[NSArray alloc]init];
    _lab_name.delegate = self;
    _lab_num.delegate = self;
    _lab_phone.delegate = self;
    
    [self.limit_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.limit_btn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#ff7e00"]] forState:UIControlStateNormal];
    [self.limit_btn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#55ff7e00"]] forState:UIControlStateSelected];
    
    [self.limit_btn addTarget:self action:@selector(limitClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self initPickView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([textField isFirstResponder]){
        [textField  resignFirstResponder];
    }
    return YES;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSLog(@"numberOfRowsInComponent");
    
    return _dataArray.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSDictionary * dic = [self.dataArray objectAtIndex:row];

    return dic[@"bankName"];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
   // NSLog(@"%@",self.dataArray[component][row]);
    
    _chooseBank = _dataArray[row];
}


-(void)limitClick{
    if ([_lab_name.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请填写名字"];
        return;
    }
    if ([_lab_num.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请填写卡号"];
        return;
    }
    if (_chooseBank == nil) {
        [MBProgressHUD showError:@"请选择银行"];
        return;
    }
    if ([_lab_phone.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请填写电话"];
        return;
    }

    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId ,@"id":[NSString stringWithFormat:@"%@",_chooseBank[@"id"]],@"flag":@"0",@"cardNum":_lab_num.text,@"carUserName":_lab_name.text,@"phone":_lab_phone.text};
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"bank_card_operator" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        
        if ([data[@"success"] boolValue]) {
            
            [MBProgressHUD showSuccess:@"添加成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
    
}

- (IBAction)bank_click:(id)sender {
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId };
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"bank_card_info_get" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        
        if ([data[@"success"] boolValue]) {
            
            _dataArray = data[@"result"];
            UIPickerView *view = [self.view viewWithTag:12345];
            [view reloadAllComponents];
            [self showBank_click];
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}
- (void)showBank_click {
    
    UIView *timeView = [self.view viewWithTag:111111];
    if (timeView.hidden == YES) {
        timeView.hidden = NO;
        
        [UIView animateWithDuration:0.5 animations:^{
            
            // 设置view弹出来的位置
            
            timeView.frame = CGRectMake(0, ScreenHeight - 260, ScreenWidth, 260);
        }];
        
    }else{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            // 设置view弹出来的位置
            
            timeView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 260);
            timeView.hidden = YES;
        }];
        
        
    }
}



- (void)initPickView{
    //初始化数据
    
//    UIView *view = [self.view viewWithTag:111111];
//    if (view != nil) {
//        [view removeFromSuperview];
//    }
    UIView *dialogView = [[UIView alloc]initWithFrame: CGRectMake(0, ScreenHeight, ScreenWidth, 260)];
    dialogView.backgroundColor = [UIColor whiteColor];
    dialogView.tag = 111111;
    dialogView.hidden = YES;
    
    UIButton * cancle = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, 60, 30)];
    [cancle setTitle:@"取消" forState:UIControlStateNormal];
    cancle.titleLabel.font = [UIFont systemFontOfSize:13 ];
    [cancle setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [cancle setTitleColor:[UIColor colorWithHexString:@"#55ff7e00"] forState:UIControlStateSelected];
    [cancle addTarget:self action:@selector(dialogBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * ok = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 70, 10, 60, 30)];
    ok.tag = 55;
    ok.titleLabel.font = [UIFont systemFontOfSize:13 ];
    [ok setTitle:@"确定" forState:UIControlStateNormal];
    [ok setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [ok setTitleColor:[UIColor colorWithHexString:@"#55ff7e00"] forState:UIControlStateSelected];
    [ok addTarget:self action:@selector(dialogBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIPickerView *pickView1 = [[UIPickerView alloc]initWithFrame:CGRectMake(10, 40,(ScreenWidth - 20) , 200)];
    //pickView1.backgroundColor = [UIColor greenColor];
    pickView1.tag = 12345;
    
    
    
    
    pickView1.showsSelectionIndicator = YES;
    
    
    
    [dialogView addSubview:cancle];
    [dialogView addSubview:ok];
    [dialogView addSubview:pickView1];
    
    [self.view addSubview:dialogView];
    
    pickView1.dataSource = self;
    pickView1.delegate = self;
    
   
    
}

-(void)dialogBtn:(UIButton *) button{
    [self showBank_click];
    if (button.tag == 55) {

        
        if (_chooseBank != nil) {
            [_lab_card setTitle:_chooseBank[@"bankName"] forState:UIControlStateNormal];
        }
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)back_click:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)touch_view:(id)sender {
    [self.view endEditing:YES];
}
- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return theImage;
}
-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
@end
